package com.wx.qiqiai.controller;

import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.wx.qiqiai.handle.Handle;
import com.wx.qiqiai.handle.HandleEnum;
import com.wx.qiqiai.service.WeiXinService;

import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;

/**
 * 微信接口入口
 * 
 * @author zhugh
 * @date 2023/04/04 20:48
 **/
@RestController
@RequestMapping("/wechat/portal")
@Slf4j
public class WxController {
    @Autowired
    private WeiXinService weiXinService;

    @Autowired
    private Map<String, Handle> handleMap;

    @ResponseBody
    @GetMapping(produces = "text/plain;charset=utf-8")
    public String authGet(@RequestParam(name = "signature", required = false) String signature,
        @RequestParam(name = "timestamp", required = false) String timestamp,
        @RequestParam(name = "nonce", required = false) String nonce,
        @RequestParam(name = "echostr", required = false) String echostr) {
        if (!StringUtils.isAnyBlank(signature, timestamp, nonce, echostr)
            && weiXinService.checkSignature(timestamp, nonce, signature)) {
            return echostr;
        }
        return "非法请求";
    }

    @ResponseBody
    @PostMapping(produces = "application/xml; charset=UTF-8")
    public String post(@RequestBody String requestBody, @RequestParam("signature") String signature,
        @RequestParam(name = "encrypt_type", required = false) String encType,
        @RequestParam(name = "msg_signature", required = false) String msgSignature,
        @RequestParam("timestamp") String timestamp, @RequestParam("nonce") String nonce) {
        log.info(
            "\n接收微信请求：[signature=[{}], encType=[{}], msgSignature=[{}],"
                + " timestamp=[{}], nonce=[{}], requestBody=[\n{}\n] ",
            signature, encType, msgSignature, timestamp, nonce, requestBody);
        if (!weiXinService.checkSignature(timestamp, nonce, signature)) {
            return "非法请求";
        }
        String out = null;
        if (encType == null) {
            // 明文传输的消息
            WxMpXmlMessage inMessage = WxMpXmlMessage.fromXml(requestBody);

            if ("event".equals(inMessage.getMsgType()) && "subscribe".equals(inMessage.getEvent())) {
                return WxMpXmlOutMessage.TEXT().fromUser(inMessage.getToUser()).toUser(inMessage.getFromUser())
                    .content("感谢关注，可以直接向我提问哦，柒柒当前接入的是GPT-3.5").build().toXml();
            }
            Handle handle = handleMap.get(HandleEnum.getHandleName(inMessage.getMsgType()));
            if (handle == null) {
                return WxMpXmlOutMessage.TEXT().fromUser(inMessage.getToUser()).toUser(inMessage.getFromUser())
                    .content("柒柒暂不支持此类型消息哦！").build().toXml();
            }
            WxMpXmlOutMessage outMessage = handle.handle(inMessage);
            out = outMessage.toXml();
        } else {
            // 加密消息，后面实现
        }
        log.info("\n回复信息：{}", out);
        return out;
    }
}
